package com.example.project.intecetper;

import com.example.project.aop.AuthLogin;
import com.example.project.exception.AuthException;
import com.example.project.utils.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
@Order(2)
public class AuthLoginIntecepter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws AuthException,Exception {

        AuthLogin annotation = null;
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //1.获取目标类上的目标注解（可判断目标类是否存在该注解）
            annotation = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), AuthLogin.class);

            //2.获取目标方法上的目标注解（可判断目标方法是否存在该注解）  方法上会进行覆盖，实现更低密度的 鉴权
            AuthLogin annotationMethod = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), AuthLogin.class);
            if (!ObjectUtils.isEmpty(annotationMethod)) {
                annotation = annotationMethod;
            }

            if (!ObjectUtils.isEmpty(annotation)) {
                AuthUtil.checkLogin(annotation);
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }


}
